package com.codetree.strategy.simple.strategy_example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付方式的策略工厂
 */
@Slf4j
@Component
public class PaymentStrategyFactory {

    /**
     * 策略池
     */
    private final Map<String, PaymentService> STRATEGY_MAP = new ConcurrentHashMap<>();

    @Resource
    private List<PaymentService> strategies;

    /**
     * Spring启动时注入所有的支付策略
     */
    @PostConstruct
    public void initStrategies() {
        for (PaymentService strategy : strategies) {
            log.info("注入策略：{}", strategy.getClass().getSimpleName());
            String type = strategy.getClass().getSimpleName()
                    .replace("Strategy", "");
            STRATEGY_MAP.put(type, strategy);
        }
    }


    /**
     * 根据上下文获取支付策略
     * @param type 上下文参数
     * @return 支付策略
     */
    public PaymentService getStrategy(String type) {
        PaymentService paymentService = STRATEGY_MAP.get(type);
        return Optional.ofNullable(paymentService)
                .orElseThrow(() -> new IllegalArgumentException("无效支付类型"));
    }

}
